package com.fg.estate.interceptor;

import com.fg.estate.bean.Admin;
import com.fg.estate.bean.Role;
import com.fg.estate.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 丰哥
 * 2022/10/18
 */
@Component
public class AdminPermissionInterceptor implements HandlerInterceptor {

    @Autowired
    private RoleService roleService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 权限认证
        // ① 获得登录后的用户信息
        Admin admin = (Admin) request.getSession().getAttribute("admin");

        System.out.println("admin = " + admin);
        System.out.println("roleService = " + roleService);

        // ② 根据用户的角色id查询角色
        Role role = roleService.selectById(admin.getRoleId());

        // ③ 根据角色进行权限认证
        if(role.getName().equals("系统管理员") || role.getName().equals("用户管理员")) {
            System.out.println("放行....");
            // 放行
            return true;
        } else {
            System.out.println("拦截....");
            // 重定向到权限不足
            response.sendRedirect(request.getContextPath() + "/permission/nopermission");
            return false;
        }


    }

}
